package jp.co.dailyReport.search.action;

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.DynaActionForm;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.search.SearchDailyReport;
import jp.co.dailyReport.search.SearchDailyReportManager;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.staff.Staff;
import java.util.Calendar;

/**
 * 日報検索の検索結果一覧ページのページ変えリンク、
 * 日報検索ページのボタン（検索、前日の日報一覧、先週の日報一覧）
 * が押されたときの処理を管理するクラスです。
 */
public class SearchDailyReportConditionAction extends Action {

	private static Logger log = Logger.getLogger(SearchDailyReportConditionAction.class);
	private String keyWord;
	private Integer projectId;
	private Integer workItemId;
	private Integer staffId;
	private Integer employmentSystem;
	private Integer startYear;
	private Integer startMonth;
	private Integer startDay;
	private Integer endYear;
	private Integer endMonth;
	private Integer endDay;
	private String startDate;
	private String endDate;
	private int maxPage;
	private int nowPage;

	/**
	 * 日報検索の検索結果一覧ページのページ変えリンク、
	 * 日報検索ページのボタン（検索、前日の日報一覧、先週の日報一覧）
	 * が押されたときの処理を行います。<BR><BR>
	 * 「検索」ボタンが押された場合の処理：<BR>
	 * 検索条件の入力チェックを行います。
	 * 検索条件にあった検索結果を取得します。<BR><BR>
	 * 「前日の日報一覧」ボタンが押された場合の処理：<BR>
	 * 前日の日報情報を取得します。<BR><BR>
	 * 「先週の日報一覧」ボタンが押された場合の処理：<BR>
	 * 先週の日報情報を取得します。
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		 throws IOException, ServletException {

		log.debug("SearchDailyReportConditionAction start");
		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		request.removeAttribute("searchDailyReportList");
		DynaActionForm searchDailyReportConditionActionForm = (DynaActionForm) form;
		SearchDailyReport[] dailyReportList = null;
		String target = null;
		ActionErrors errors = new ActionErrors();
		ArrayList searchDailyReportList = new ArrayList();
		Map params = new HashMap();

		if(request.getParameter("search") != null) {
			params.put("search", "search");
			setSearchCondition(searchDailyReportConditionActionForm);
		} else if(request.getParameter("yesterday") != null) {
			params.put("yesterday", "yesterday");
			setSearchYesterdayCondition(searchDailyReportConditionActionForm);
		} else if(request.getParameter("lastWeek") != null) {
			params.put("lastWeek", "lastWeek");
			setSearchLastWeekCondition(searchDailyReportConditionActionForm);
		}

		/* 条件項目チェック */
		if(checkSearchDailyReportCondition()){
			 /* OK */
			target = "list";
			//日報検索条件が全てなしの場合のチェック
			int conditionStatus = 0;
			if(keyWord.length()==0) conditionStatus++;
			if(projectId.intValue()==0) conditionStatus++;
			if(workItemId.intValue()==0) conditionStatus++;
			if(staffId.intValue()==0) conditionStatus++;
			if(employmentSystem.intValue()==-1) conditionStatus++;
			if(startDate.equals("00000000")) conditionStatus++;
			if(endDate.equals("00000000")) conditionStatus++;
			if(conditionStatus != SearchDailyReport.CONDITION_STATUS) {
				SearchDailyReportManager searchDailyReportManager = new SearchDailyReportManager();
				searchDailyReportManager.setStaff(staff);
				/* 検索条件設定 */
				/* キーワード */
				searchDailyReportManager.setKeyWord(keyWord);
				/* プロジェクト名 */
				searchDailyReportManager.setProjectId(projectId.intValue());
				/* 作業項目 */
				searchDailyReportManager.setWorkItemId(workItemId.intValue());
				/* 氏名 */
				searchDailyReportManager.setStaffId(staffId.intValue());
				/* 雇用形態 */
				searchDailyReportManager.setEmploymentSystem(employmentSystem.intValue());
				/* 検索期間 */
				searchDailyReportManager.setStartWorkDate(startDate);
				searchDailyReportManager.setEndWorkDate(endDate);
				try {
					if(request.getParameter("changePage")==null){
						session.removeAttribute("searchDailyReportResult");
						dailyReportList = searchDailyReportManager.load();
						session.setAttribute("searchDailyReportResult",dailyReportList);
					}else{
						dailyReportList = (SearchDailyReport[])session.getAttribute("searchDailyReportResult");
					}
				} catch(DataUnavailableException due) {
					log.error(due.getMessage());
				}

				if(maxPage == 0){
					int searchResultCount = dailyReportList.length;
					maxPage = searchResultCount/SearchDailyReport.PAGE_COUNT;
					if(searchResultCount%SearchDailyReport.PAGE_COUNT!=0){
						maxPage = maxPage + 1;
					}
					searchDailyReportConditionActionForm.set("maxPage", new Integer(maxPage));
					if(maxPage != 0){
						nowPage = 1;
						searchDailyReportConditionActionForm.set("nowPage", new Integer(1));
					}
				}
				if(maxPage != 0) {
					if(nowPage < maxPage) {
						for(int i = ((nowPage - 1)*SearchDailyReport.PAGE_COUNT);i<(nowPage*SearchDailyReport.PAGE_COUNT);i++) {
							searchDailyReportList.add(dailyReportList[i]);
						}
					}else if(nowPage==maxPage){
						for(int i = ((nowPage - 1)*SearchDailyReport.PAGE_COUNT);i<dailyReportList.length;i++) {
							searchDailyReportList.add(dailyReportList[i]);
						}
					}
				}
				request.setAttribute("searchDailyReportList", (SearchDailyReport[])searchDailyReportList.toArray(new SearchDailyReport[0]));
				//週報検索結果のリンク先ページに渡すパラメータ設定
				params.put("keyWord", "keyWord");
				params.put("projectId", projectId);
				params.put("workItemId", workItemId);
				params.put("staffId", staffId);
				params.put("employmentSystem", employmentSystem);
				params.put("startYear", startYear);
				params.put("startMonth", startMonth);
				params.put("startDay", startDay);
				params.put("endYear", endYear);
				params.put("endMonth", endMonth);
				params.put("endDay", endDay);
				params.put("maxPage", String.valueOf(maxPage));
				params.put("changePage", "changePage");
				request.setAttribute("params", params);
			} else {
				target = "error";
				errors.add("searchConditionRequired",new ActionError("errors.search.dailyReportCondition.required"));
				saveErrors(request,errors);
			}
		}else{
			/* error */
			target = "error";
			errors.add("searchConditionInvalid",new ActionError("errors.search.dailyReportCondition.invalid"));
			saveErrors(request,errors);
		}

		log.debug("SearchDailyReportConditionAction end");
		return mapping.findForward(target);
	}

	private void setSearchCondition(DynaActionForm form) {
		/* 検索項目 */
		this.keyWord = Utilities.convUniqueCharacter((String)form.get("keyWord")).trim();
		this.projectId = (Integer)form.get("projectId");
		this.workItemId = (Integer)form.get("workItemId");
		this.staffId = (Integer)form.get("staffId");
		this.employmentSystem = (Integer)form.get("employmentSystem");
		this.startYear = (Integer)form.get("startYear");
		this.startMonth =(Integer)form.get("startMonth");
		this.startDay = (Integer)form.get("startDay");
		this.endYear = (Integer)form.get("endYear");
		this.endMonth = (Integer)form.get("endMonth");
		this.endDay = (Integer)form.get("endDay");
		this.maxPage = ((Integer)form.get("maxPage")).intValue();
		this.nowPage = ((Integer)form.get("nowPage")).intValue();
		return;
	}

	private void setSearchYesterdayCondition(DynaActionForm form) {
		/* 前日 */
		/* 検索項目 */
		this.keyWord = "";
		this.projectId = new Integer(0);
		this.workItemId = new Integer(0);
		this.staffId = new Integer(0);
		this.employmentSystem = new Integer(-1);

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		this.startYear = new Integer(cal.get(Calendar.YEAR));
		this.startMonth = new Integer(cal.get(Calendar.MONTH) + 1);
		this.startDay = new Integer(cal.get(Calendar.DATE));
		this.endYear = new Integer(cal.get(Calendar.YEAR));
		this.endMonth = new Integer(cal.get(Calendar.MONTH) + 1);
		this.endDay = new Integer(cal.get(Calendar.DATE));
		this.maxPage = ((Integer)form.get("maxPage")).intValue();
		this.nowPage = ((Integer)form.get("nowPage")).intValue();
		return;
	}

	private void setSearchLastWeekCondition(DynaActionForm form) {

		/* 先週(月曜～日曜)*/
		/* 検索項目 */
		this.keyWord = "";
		this.projectId = new Integer(0);
		this.workItemId = new Integer(0);
		this.staffId = new Integer(0);
		this.employmentSystem = new Integer(-1);

		Calendar cal = Calendar.getInstance();
		int currentDay = cal.get(Calendar.DAY_OF_WEEK);
		int startDay = 0 - currentDay - 5;

		cal.add(Calendar.DATE, startDay);
		this.startYear = new Integer(cal.get(Calendar.YEAR));
		this.startMonth = new Integer(cal.get(Calendar.MONTH) + 1);
		this.startDay = new Integer(cal.get(Calendar.DATE));

		cal.add(Calendar.DATE, 6);
		this.endYear = new Integer(cal.get(Calendar.YEAR));
		this.endMonth = new Integer(cal.get(Calendar.MONTH)+1);
		this.endDay = new Integer(cal.get(Calendar.DATE));
		this.maxPage = ((Integer)form.get("maxPage")).intValue();
		this.nowPage = ((Integer)form.get("nowPage")).intValue();
		return;
	}


	private boolean checkSearchDailyReportCondition(){

		if(keyWord == null)
			keyWord = "";
		if(projectId == null)
			projectId = new Integer(0);
		if(workItemId == null)
			workItemId = new Integer(0);
		if(staffId == null)
			staffId = new Integer(0);
		if(employmentSystem == null)
			employmentSystem = new Integer(-1);
		if(startYear == null)
			startYear = new Integer(0);
		if(startMonth == null)
			startMonth = new Integer(0);
		if(startDay == null)
			startDay = new Integer(0);
		if(endYear == null)
			endYear = new Integer(0);
		if(endMonth == null)
			endMonth = new Integer(0);
		if(endDay == null)
			endDay = new Integer(0);

		/* 検索期間チェック */
		String startDateY;
		String startDateM;
		String startDateD;
		String endDateY;
		String endDateM;
		String endDateD;
		
		if(startYear.intValue() == 0){
			startDateY = "0000";
		}else{
			startDateY = startYear.toString();
		}
		if(startMonth.intValue() >= 0 && startMonth.intValue() <= 9){
			startDateM = "0" + this.startMonth.intValue();
		}else{
			startDateM = startMonth.toString();
		}
		if(startDay.intValue() >= 0 && startDay.intValue() <= 9){
			startDateD = "0" + startDay.intValue();
		}else{
			startDateD = startDay.toString();
		}
		if(endYear.intValue() == 0){
			endDateY = "0000";
		}else{
			endDateY = endYear.toString();
		}
		if(endMonth.intValue() >= 0 && endMonth.intValue() <= 9){
			endDateM = "0" + endMonth.intValue();
		}else{
			endDateM = endMonth.toString();
		}
		if(endDay.intValue() >= 0 && endDay.intValue() <= 9){
			endDateD = "0" + endDay.intValue();
		}else{
			endDateD = endDay.toString();
		}
		startDate = startDateY + startDateM + startDateD;
		endDate = endDateY + endDateM + endDateD;

		/* start年月日 -> 日のみ */
		if(startDateY.equals("0000")
			&& startDateM.equals("00")
			&& !startDateD.equals("00")){
				return false;
		}

		/* start年月日 -> 月のみ */
		if(startDateY.equals("0000")
			&& !startDateM.equals("00")
			&& startDateD.equals("00")){
				return false;
		}

		/* start年月日 -> 月日のみ */
		if(startDateY.equals("0000")
			&& !startDateM.equals("00")
			&& !startDateD.equals("00")){
				return false;
		}

		/* start年月日 -> 年日のみ */
		if(!startDateY.equals("0000")
			&& startDateM.equals("00")
			&& !startDateD.equals("00")){
				return false;
		}

		/* end年月日 -> 日のみ */
		if(endDateY.equals("0000")
			&& endDateM.equals("00")
			&& !endDateD.equals("00")){
				return false;
		}

		/* end年月日 -> 月のみ */
		if(endDateY.equals("0000")
			&& !endDateM.equals("00")
			&& endDateD.equals("00")){
				return false;
		}

		/* end年月日 -> 月日のみ */
		if(endDateY.equals("0000")
			&& !endDateM.equals("00")
			&& !endDateD.equals("00")){
				return false;
		}

		/* end年月日 -> 年日のみ */
		if(!endDateY.equals("0000")
			&& endDateM.equals("00")
			&& !endDateD.equals("00")){
				return false;
		}

		/* start年月日 > end年月日 */
		if(!endDate.equals("00000000")
			&& startDate.compareTo(endDate) > 0){
			return false;
		}

		return true;
	}

}
